<template>
    <div>
        <el-card>
            <CategorySelector :disabled="isEdit" />
        </el-card>
        <el-card class="mt-10">
            <!-- 列表页 -->
            <div v-if="!isEdit">
                <el-button type="primary" :icon="Plus" @click="addAttr" :disabled="!categoryStore.category3Id">添加属性
                </el-button>
                <el-table :data="attrInfoList" class="mt-10" border>
                    <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
                    <el-table-column label="属性名" width="160" prop="attrName"></el-table-column>
                    <el-table-column label="属性值列表">
                        <template #default="{ row, $index }">
                            <el-tag type="success" v-for="attrVal in row.attrValueList" class="mr-5">{{
                            attrVal.valueName }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="140">
                        <template #default="{ row, $index }">
                            <el-button v-permissionBtn="'btn.Attr.update'" type="warning" :icon="Edit" size="small" @click="handleEdit(row)"></el-button>
                            <el-popconfirm :title="`请确认是否删除[${row.attrName}]?`" @confirm="handleDelete(row)">
                                <template #reference>
                                    <el-button v-permissionBtn="'btn.Attr.remove'" type="danger" :icon="Delete" size="small"></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 编辑页 -->
            <div v-else>
                <el-form :inline="true" :model="attrForm">
                    <el-form-item label="属性名">
                        <el-input type="text" placeholder="请输入属性名" v-model="attrForm.attrName"></el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary" @click="addAttrValue" :disabled="!attrForm.attrName">添加属性值</el-button>
                <el-button @click="isEdit = false">取消</el-button>
                <el-table :data="attrForm.attrValueList" border class="mt-10 mb-10">
                    <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template #default="{ row, $index }">
                            <el-input v-if="row.inputVisible" type="text" size="small" v-model="row.valueName"
                                ref="inputRef" @blur="inputBlur(row, $index)"></el-input>
                            <div v-else @click="inputFocus(row)">{{ row.valueName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80">
                        <template #default="{ row, $index }">
                            <el-popconfirm :title="`请确认是否删除[${row.valueName}]?`" @confirm="handleDeleteVal($index)">
                                <template #reference>
                                    <el-button type="danger" :icon="Delete" size="small"></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" @click="onsave"
                    :disabled="!(attrForm.attrName && attrForm.attrValueList.length)">保存</el-button>
                <el-button @click="isEdit = false">取消</el-button>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { nextTick, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import attrApi, { type attrInfoModel, type attrValueModel } from '@/api/attr'
import useCategoryStore from '@/stores/category'
import { Delete, Edit, Plus } from '@element-plus/icons-vue';
import { cloneDeep } from 'lodash';
const categoryStore = useCategoryStore()
const attrInfoList = ref<attrInfoModel[]>()
const isEdit = ref(false)
const inputRef = ref()
// 用于初始化attrForm
const initAttrForm = (): attrInfoModel => ({
    attrName: '',
    attrValueList: [],
    categoryId: categoryStore.category3Id as number,
    categoryLevel: 3,
})
const attrForm = ref<attrInfoModel>(initAttrForm())
// watch监听category3Id的变化,获取平台属性列表
watch(() => categoryStore.category3Id, (nval, oval) => {
    if (nval) {
        getAttrInfoList();
    } else {
        attrInfoList.value = []
    }
}, { immediate: true })
// 获取平台属性
const getAttrInfoList = async () => {
    let { category1Id, category2Id, category3Id } = categoryStore;
    try {
        let result = await attrApi.getAttrInfo(category1Id as number, category2Id as number, category3Id as number);
        attrInfoList.value = result;
    } catch (error) {
        ElMessage.error('获取平台属性失败,请重试')
    }
}
// 添加属性
const addAttr = () => {
    isEdit.value = true;
    attrForm.value = initAttrForm();
}
// 添加属性值
const addAttrValue = () => {
    attrForm.value.attrValueList.push({
        valueName: '',
        inputVisible: true
    })
    // 点击按钮时,聚焦到输入框
    nextTick(() => {
        inputRef.value.focus();
    })
}
// 保存数据
const onsave = async () => {
    try {
        await attrApi.saveAttrInfo(attrForm.value)
        isEdit.value = false;
        getAttrInfoList();
    } catch (error) {
        ElMessage.error('保存失败,请重试')
    }
}
// 编辑数据
const handleEdit = (row: attrInfoModel) => {
    attrForm.value = cloneDeep(row);
    isEdit.value = true;
}
// 删除属性数据
const handleDelete = async (row: attrInfoModel) => {
    try {
        await attrApi.deleteAttr(row.id as number);
        getAttrInfoList();
    } catch (error) {
        ElMessage.error('删除属性失败,请重试')
    }
}
// 删除属性值
const handleDeleteVal = (index: number) => {
    attrForm.value.attrValueList.splice(index, 1)
}

// 输入框失焦
const inputBlur = (row: attrValueModel, index: number) => {
    row.inputVisible = false;
    if (!row.valueName) {
        attrForm.value.attrValueList.splice(index, 1);
        ElMessage.error('属性值不能为空,请重新输入!')
    }
    const isRepeat = attrForm.value.attrValueList.some((item, idx) => {
        if (index !== idx) {
            return item.valueName === row.valueName
        }
    })
    if (isRepeat) {
        attrForm.value.attrValueList.splice(index, 1)
        ElMessage.error('属性值重复,请重新输入')
    }
}
// 点击属性值,显示输入框,聚焦
const inputFocus = (row: attrValueModel) => {
    row.inputVisible = true;
    nextTick(() => {
        inputRef.value.focus();
    })
}

</script>

<style scoped>

</style>